<template>
  <div>
    <el-form ref="ruleForm" label-position="right" size="small" label-width="110px" class="base-search-more">
       <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="所属区域">
            <el-select style="width:100%" v-model="form.agentId" filterable default-first-option placeholder="--区域--" @change="getmenuList">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部门关键字">
            <el-input style="width: 100%" placeholder="部门关键字" v-model="params.rname" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent?12:18" style="text-align: right">
          <el-form-item label-width="0">
            <el-button type="primary" icon="el-icon-search" @click="$refs.pagination.handleSizeChange(10)">查询</el-button>
            <el-button type="primary" plain icon="el-icon-plus" @click="addSction(1)">新增部门</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-table :data="tableData.list" stripe style="width: 100%">
        <el-table-column prop="rname" label="部门名称" width="140" align="center" />
        <el-table-column prop="info" label="描述" min-width="150" align="left" />
        <el-table-column label="操作人" min-width="240" align="left">
          <template slot-scope="scope">
            <div class="text-over2">{{scope.row.baseUsers|catpion}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
        <el-table-column prop="updateTime" label="修改时间" width="160" align="center" />
        <el-table-column  label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button class="el-text-check" @click="handleClickAllot(scope.row)" type="text" size="mini">分配权限</el-button>
            <el-button class="el-text-warning" @click="addSction(2,scope.row)" type="text" style="color:#f56c6c" size="mini">编辑部门</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pt-table-loading v-show="isloadingTable" />
      <pt-pagination ref="pagination" :total="tableData.total" @listeningEvent="triggerEvent" />
    </div>
    <el-dialog :title="addOrEdit+'部门'" v-dialogDrag :visible.sync="dialogTableVisible1" width="600px" height="500px" :close-on-press-escap="true">
      <el-form :model="form" ref="ruleForm" label-width="100px" size="small">
        <el-form-item label="所属区域" prop="agentId" :rules="[{ required: true, message: '请在列表页面上选择区域', trigger: 'change' }]">
          <el-row type="flex">
            <el-select v-model="form.agentId" :disabled="true">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-tooltip class="item" effect="dark" content="此处和列表页面同步,若想更改请在列表页面更改" placement="top-start">
              <el-button type="text" icon="el-icon-question" />
            </el-tooltip>
          </el-row>
        </el-form-item>
        <el-form-item label="部门名称" prop="rname" :rules="[{ required: true, message: '名称未填', trigger: 'blur' }]">
          <el-input v-model="form.rname" placeholder="输入部门的角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="info" :rules="[{ required: true, message: '名称未填', trigger: 'blur' }]">
          <el-input type="textarea" :rows="2" placeholder="请输入角色权限和职责描述" v-model="form.info" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isloadingRole" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div v-show="dialogTableVisible2">  <!--委托 v-show打开关闭弹窗，让tree默认渲染，不然第一次报错-->
      <el-dialog title="分配权限" v-dialogDrag :visible="true" width="600px" height="500px"
        @close="dialogTableVisible2=false" :modal="false" :close-on-click-modal="false">
        <div class="tree">
          <el-tree :data="roleList" ref="tree" show-checkbox node-key="pid" :props="resourceProps">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span><span class="expanded"></span>{{node.label}}</span>
            </span>
          </el-tree>
          <div style="text-align: right;margin-top:20px">
            <el-button @click="dialogTableVisible2 = false" plain>取消</el-button>
            <el-button type="primary" @click="saveRoleJurtion()" :loading="isloadingRoleJurtion">确认</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        addOrEdit: '添加',  //添加 修改文本提示
        isloadingRole: false,//保存角色
        isloadingRoleJurtion: false,//保存角色权限
        isloadingTable: false, //表单等待
        editId: '', // 被编辑角色的ID
        editIdJurtion: '', //被编辑权限的角色的ID
        form: { // 新增或修改角色
          rname: '',
          info: '',
          agentId: ''
        },
        roleList: [], // 编辑内权限列表
        resourceProps: {
          children: "subList",
          label: "pname"
        },
        defaultChecked: [],
        dialogTableVisible1: false, // 对话框
        dialogTableVisible2: false,
        params: { // 表格查询
          page: 0,
          size: 10,
          rname: '',
        },
        tableData: {} //表单数据
      
      }
    },
    filters:{
      catpion(arr){
        if(arr.length>0){
          let list = []
          arr.forEach((item,index)=>{
            list.push(item.realname)
          })
          return list.join('、')
        }else {
          return ''
        }
      }
    },
    computed: {
      restaurants() { // 区域数据
        return this.$store.state.agentListAll
      }
    },
    watch: {
      restaurants: {
        handler(val, oldVal) {
          if (val && val.length) {
            this.form.agentId = val[0].id
            this.getmenuList(this.form.agentId)
          }
        },
        deep: true
      }
    },
    methods: {
      addSction(type, row) { // 打开对话框，开始新增或修改
        if (type == 1) {
          this.addOrEdit = '添加'
          this.form.rname = ''
          this.form.info = ''
          this.editId = ''
          this.dialogTableVisible1 = true
        } else if (type == 2) {
          this.addOrEdit = '编辑'
          this.form.rname = row.rname ? row.rname.toString() : ''
          this.form.info = row.info ? row.info.toString() : ''
          this.editId = row.rid
          this.dialogTableVisible1 = true
        }
      },
      submitForm(formName) { // 新增和保存广告
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.form }
            this.isloadingRole = true
            if (this.editId) {
              params.rid = this.editId
              this.$http.post('/server/role/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改角色成功！'})
                  this.dialogTableVisible1 = false
                  this.getTableList()
                }
              }).finally(err => { this.isloadingRole = false })
            } else {
              this.$http.post('/server/role/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '新增角色成功！'})
                  this.dialogTableVisible1 = false
                  this.getTableList()
                }
              }).finally(() => { this.isloadingRole = false })
            }
          }
        })
      },
      getmenuList(id) { //获取权限列表
        let params = {agentId: id}
        this.roleList = []
        this.isloadingTable = true
        this.$http.get('/server/purview/select?'+this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.roleList = res.data.data
            this.getTableList()
            this.$refs.pagination.handleSizeChange(10)
          }
        }).finally(() => { this.isloadingTable = false })
      },
      getTableList() { //获取表数据
        this.isloadingTable = true
        const params = { ...this.params }
        params.agentId = this.form.agentId
        this.$http.get('/server/role/list?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data.data
          }
        }).finally(() => { this.isloadingTable = false })
      },
      saveRoleJurtion() { //保存角色权限
        this.isloadingRoleJurtion = true
        let params = {
          rid: this.editIdJurtion,
          pIds: this.$refs.tree.getCheckedKeys(),
          agentId:this.form.agentId,
        }
        let half = this.$refs.tree.getHalfCheckedKeys()
        if(half.length >0){
          params.pIds = params.pIds.concat(half)
        }
        params.pIds = params.pIds.join(',')
        this.$http.get('/server/role/setPurviewsById?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.dialogTableVisible2 = false
            this.getTableList()
          }
        }).finally(() => { this.isloadingRoleJurtion = false })
      },
      handleClickAllot(row) { //显示角色权限
        this.dialogTableVisible2 = true
        this.editIdJurtion = row.rid
        this.$refs.tree.setCheckedKeys(row.purviewIdList)//获取已经设置的资源后渲染
      },
      handleClickDel(row) { //删除角色
       
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.size = val
        }
        this.getTableList()
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length) {
        this.form.agentId = this.restaurants[0].id
        this.getmenuList(this.restaurants[0].id)
      }
    },
  }
</script>
<style scoped>
  .tree .el-tree {
    padding: 10px;
    border: 1px solid #e2e2e2;
  }
  .tree .el-tree .el-tree-node__content {
    line-height: 205px;
  }
  .save-a li {
    line-height: 60px;
  }
  .save-a li span {
    width: 120px;
    text-align: left;
  }
  .text-over2{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
</style>
